import time
import logging

import erniebot

from .base import Chat
from .config import ERNIE_CONFIG, SYSTEM_PROMPT


logger = logging.getLogger("chat")


class ErnieChat(Chat):

    def __init__(self, name="ernie"):
        erniebot.ak = ERNIE_CONFIG["ak"]
        erniebot.sk = ERNIE_CONFIG["sk"]

        super().__init__(name)
        logger.info("ErnieChat initialized.")

    def chat(self, question):
        logger.info(f"{ERNIE_CONFIG['debug']=}")
        logger.info(f"{question=}")
        question = SYSTEM_PROMPT + question
        self.history.append({
            "role": "user",
            "content": question,
        })
        logger.info(f"{self.history=}")
        debug=True

        if not ERNIE_CONFIG["debug"]:
            try:
                response = erniebot.ChatCompletion.create(
                    model="ernie-bot-turbo",
                    messages=self.history,
                )
            except erniebot.errors.RequestLimitError:
                logger.warning("Request limit reached.")
                return "[Error %s] Request limit reached." \
                    % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            logger.info(f"{response=}")
            answer = response.result
        else:
            answer = "Text text here because debug=True"
        logger.info(f"{answer[:50]=}")

        self.history.append({
            "role": "assistant",
            "content": answer,
        })
        logger.info(f"{self.history=}")
        return answer

